package etcd

import (
	"context"
	"encoding/json"
	"logAgent/utils"
	"time"

	"go.etcd.io/etcd/clientv3"
)

//LogEntry 日志信息
type LogEntry struct {
	Path  string //日志路径
	Topic string //日志要传递到kafka那个topic
}

var (
	cli *clientv3.Client
)

//Init 初始化etcd
func Init(addr string, timeout time.Duration) error {
	var err error
	cli, err = clientv3.New(clientv3.Config{
		Endpoints:   []string{addr},
		DialTimeout: timeout,
	})
	if err != nil {
		utils.Log.Error("初始化etcd失败: ", err)
		return err
	}
	return nil
}

//GetLogConf 获取日志文件信息
func GetLogConf(key string) ([]*LogEntry, error) {
	//get
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	resp, err := cli.Get(ctx, key)
	cancel()

	if err != nil {
		utils.Log.Error("etcd get操作失败: ", err)
		return nil, err
	}

	var logEntries []*LogEntry
	for _, v := range resp.Kvs {
		err := json.Unmarshal(v.Value, &logEntries)
		if err != nil {
			utils.Log.Error("json反序列化失败: ", err)
			return nil, err
		}
	}
	return logEntries, nil
}

//WatchConf 监控配置
func WatchConf(key string, newConfChan chan<- []*LogEntry) {
	wc := cli.Watch(context.Background(), key)
	for v := range wc {
		for _, k := range v.Events {
			//发送
			var logEntries []*LogEntry
			if k.Type != clientv3.EventTypeDelete {
				err := json.Unmarshal(k.Kv.Value, &logEntries)
				if err != nil {
					utils.Log.Error("json反序列化失败: ", err)
					continue
				}
			}
			newConfChan <- logEntries
		}
	}
}
